package org.example.myspringboot.service;

import org.example.myspringboot.pojo.User;
import org.example.myspringboot.pojo.dto.UserDto;
import org.example.myspringboot.repository.UserRepossitory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service//Spring会在启动时扫描这个类，并创建一个对应的Bean实例。
// 这个Bean实例可以被Spring容器中的其他组件通过依赖注入的方式使用。
     public class UserService implements IUserService {

    @Autowired//自动装配 Spring 容器中的 Bean，自动注入依赖
    UserRepossitory userRepossitory;
    @Override
    public User add(UserDto userDto) {
           User user = new User();
           BeanUtils.copyProperties(userDto, user);

         return  userRepossitory.save(user);

    }

    @Override
    public User getUser(Integer userId) {

        return userRepossitory.findById(userId).orElseThrow(()->{
            throw new IllegalArgumentException("用户不存在,参数异常！");
        });
    }

    @Override
    public User edit(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto, user);

        return userRepossitory.save(user);
    }

    @Override
    public void delete(Integer userId) {

         userRepossitory.deleteById(userId);

    }
}
